package com.chookss.mvp.presenter;

import android.app.Activity;
import android.graphics.Bitmap;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.chookss.MyApp;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.home.entity.HomeBannerEntity;
import com.chookss.home.entity.KnowledgeEntity;
import com.chookss.home.entity.NavigationEntity;
import com.chookss.home.entity.NewsEntiry;
import com.chookss.home.entity.UnReadMessageEntity;
import com.chookss.home.entity.WatermarkEntity;
import com.chookss.mine.entity.MineInfoEntity;
import com.chookss.mvp.view.IHomepageView;
import com.chookss.tools.FileUtilss;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author sunwei
 * email：tianmu19@gmail.com
 * date：2019/3/28 11:58
 * package：com.youtoo.mvp.presenter
 * version：1.0
 * <p>description：    首页          </p>
 */
public class HomePagePresenter extends BasePresenter<IHomepageView> {


    /**
     * 初始化，默认attachview
     *
     * @param context
     * @param mvpView
     */
    public HomePagePresenter(Activity context, IHomepageView mvpView) {
        super(context, mvpView);
    }

    public void getMineInfo() {
//        获取个人信息
        Map<String, String> allmap = new HashMap<>();
        allmap.put("employeeCode", new ShareUtils().getString(mContext, StaticClass.EMPLOYEECODE, ""));
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<MineInfoEntity>>() {
        }.getType(), null, Urls.getMyInfo, SignUtils2.makeSignStr(allmap), false, new ObserverCallback<MineInfoEntity>() {
            @Override
            public void onSuccess(MineInfoEntity data) throws Exception {
                if (isViewAttached()) {
                    mvpView.loadMineInfo(data);
                }
            }

            @Override
            public void onError(String errorMsg) {
//                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    public void getAllBanner() {
        //获取轮播
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<HomeBannerEntity>>>() {
        }.getType(), null, Urls.getAllBanner, SignUtils2.makeSignStr(null), false, new ObserverCallback<List<HomeBannerEntity>>() {
            @Override
            public void onSuccess(List<HomeBannerEntity> data) {
                if (isViewAttached()) {
                    mvpView.loadBanner(data);
                }
            }

            @Override
            public void onError(String errorMsg) {
//                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    public void getNotReadMessageByEmployee() {
        //获取未读消息
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<UnReadMessageEntity>>>() {
        }.getType(), null, Urls.getNotReadMessageByEmployee, SignUtils2.makeSignStr(null), false, new ObserverCallback<List<UnReadMessageEntity>>() {
            @Override
            public void onSuccess(List<UnReadMessageEntity> data) {
                if (isViewAttached()) {
                    mvpView.loadNotReadMessage(data);
                }
            }

            @Override
            public void onError(String errorMsg) {
//                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    public void getNewsList(int pageNum) {
        //获取新闻列表
        Map<String, String> allmap = new HashMap<>();
        allmap.put("pageNum", pageNum + "");
        allmap.put("pageSize", "20");
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<List<NewsEntiry>>>() {
        }.getType(), null, Urls.newsList, SignUtils2.makeSignStr(allmap), false, new ObserverCallback<List<NewsEntiry>>() {
            @Override
            public void onSuccess(List<NewsEntiry> data) {
                if (isViewAttached()) {
                    mvpView.loadNewsList(data);
                }
            }

            @Override
            public void onError(String errorMsg) {
                mvpView.loadNewsList(null);
            }
        });
    }
    public void getCount() {
        //加载公告未读数量
        MyHttpRequest.getDefault().getRequestCompat(null, Urls.noticeCount, SignUtils2.makeSignStr(null), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {
                if (isViewAttached()) {
                    try {
                        JSONObject jsonObject = new JSONObject(data);
                        if ("200".equals(jsonObject.getString("code"))) {
                            mvpView.loadCount(jsonObject.getString("data"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(String errorMsg) {
            }
        });
    }

    public void getMyWorkList() {
        //获取代办信息
        MyHttpRequest.getDefault().getRequestCompat(null, Urls.homepageMyWorkList, SignUtils2.makeSignStr(null), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {
                if (isViewAttached()) {
                    try {
                        JSONObject jsonObject = new JSONObject(data);
                        if ("200".equals(jsonObject.getString("code"))) {
                            JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                            mvpView.loadMyWorkList(jsonObject1.getString("bindingWx"), jsonObject1.getString("taskNum"), jsonObject1.getString("workNum"), jsonObject1.getString("mouthPlanNum"), jsonObject1.getString("dayPlanNum"), jsonObject1.getString("interviewNum"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(String errorMsg) {
            }
        });
    }

    public void getWatermarkList() {
        //获取水印
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<WatermarkEntity>>>() {
        }.getType(), null, Urls.selectAppWatermarkList, SignUtils2.makeSignStr(null), false, new ObserverCallback<List<WatermarkEntity>>() {
            @Override
            public void onSuccess(List<WatermarkEntity> data) {
                if (isViewAttached()) {
                    XJson.setWatermarkList(mContext, data);
                    for (int i = 0; i < data.size(); i++) {
                        if ("1".equals(data.get(i).getStatusCd()) && !Utils.isNull(data.get(i).getCompanyLogoBlack())) {
                            try {
                                Glide.with(mContext).asBitmap().skipMemoryCache(true)
                                        .diskCacheStrategy(DiskCacheStrategy.NONE).load(data.get(i).getCompanyLogo())
                                        .into(new SimpleTarget<Bitmap>() {
                                            @Override
                                            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                                FileUtilss.saveBmpToSd(mContext,
                                                        resource, "watermark.jpg");
                                            }
                                        });
                                Glide.with(mContext).asBitmap().skipMemoryCache(true)
                                        .diskCacheStrategy(DiskCacheStrategy.NONE).load(data.get(i).getCompanyLogoBlack())
                                        .into(new SimpleTarget<Bitmap>() {
                                            @Override
                                            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                                FileUtilss.saveBmpToSd(mContext,
                                                        resource, "watermarkBlack.jpg");
                                            }
                                        });
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            return;
                        }
                    }
                }
            }

            @Override
            public void onError(String errorMsg) {
            }
        });
    }

    public void getOSSkey() {
        //获取oss上传数据
        MyHttpRequest.getDefault().getRequestCompat(null, Urls.getUploadId, SignUtils2.makeSignStr(null), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {
                if (isViewAttached()) {
                    try {
                        JSONObject jsonObject = new JSONObject(data);
                        if ("200".equals(jsonObject.getString("code"))) {
                            JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                            String accessKeyId = jsonObject1.getString("accessKeyId");
                            String accessKeySecret = jsonObject1.getString("accessKeySecret");
                            MyApp.accessKeyId = accessKeyId.substring(3, accessKeyId.length() - 3).trim();
                            MyApp.accessKeySecret = accessKeySecret.substring(3, accessKeySecret.length() - 3).trim();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(String errorMsg) {
            }
        });
    }

    public void getNavigations() {
        //获取导航
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<NavigationEntity>>>() {
        }.getType(), null, Urls.selectByRole, SignUtils2.makeSignStr(null), false, new ObserverCallback<List<NavigationEntity>>() {
            @Override
            public void onSuccess(List<NavigationEntity> data) {
                if (isViewAttached()) {
                    mvpView.loadNavigationsList(data);
                }
            }

            @Override
            public void onError(String errorMsg) {
                mvpView.loadNavigationsList(null);
            }
        });

    }

    public void checkLogin() {
        //每日登录
        Map<String, String> map = new HashMap<>();
        String pushId = MyApp.PUSHID;
        if (Utils.isNull(pushId)) {
            pushId = new ShareUtils().getString(mContext, StaticClass.PUSHID, "");
        }
        map.put("alibabaUid", pushId);
        map.put("systemType", "1");
        MyHttpRequest.getRequest(Urls.checkLogin, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
            }
        });
    }


    public void getCostConfig() {
        //获取计费配置接口
        MyHttpRequest.getDefault().getRequestCompat(null, Urls.getCostConfig, SignUtils2.makeSignStr(null), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {
                if (isViewAttached()) {
                    try {
                        JSONObject jsonObject = new JSONObject(data);
                        if ("200".equals(jsonObject.getString("code"))) {
                            JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                            MyApp.longVideoEvery = Utils.changeNumber(jsonObject1.getString("longVideoEvery"));
                            MyApp.smalVideoEvery = Utils.changeNumber(jsonObject1.getString("smalVideoEvery"));
                            MyApp.smalVideoEvery = Utils.changeNumber(jsonObject1.getString("smalVideoEvery"));
                            MyApp.smalVideoEvery = Utils.changeNumber(jsonObject1.getString("smalVideoEvery"));
                            new ShareUtils().putString(mContext, StaticClass.PHONE_FLAG,  jsonObject1.getString("phoneFlag"));
                            new ShareUtils().putString(mContext, StaticClass.LP_FLAG,  jsonObject1.getString("lpFlag"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(String errorMsg) {
            }
        });
    }
    //知识库接口太慢，缓存作用
    public void getCatalogData() {
        Map<String, String> map = new HashMap<>();
        map.put("catalogType", "0");
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<List<KnowledgeEntity>>>() {
        }.getType(), null, Urls.selectCatalogTreeZsk, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<KnowledgeEntity>>() {
            @Override
            public void onSuccess(List<KnowledgeEntity> data) {
                if (data != null) {
                  XJson.setKnowledgeEntity(mContext,data);
                }
            }

            @Override
            public void onError(String errorMsg) {
            }
        });
    }
}
